package com.pansoft.openplanet.util;

import android.annotation.SuppressLint;
import android.content.Context;

import com.efounder.chat.utils.RSAUtil;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.ToastUtil;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.widget.TCLoadingDataView;

import org.json.JSONObject;

import java.util.HashMap;

/**
 * 兼容旧版本apk相关操作
 * 检查用户rsa 密钥信息
 * 没有这些信息的为用户生成并保存
 */
public class CompatibleOldVersionUtil {
    private static final String TAG = "CompatibleOldVersionUtil";


    public static void checkLocalInfoIsFull(Context context, CheckListener listener) {
        if (EnvironmentVariable.getProperty(RSAUtil.getCurrentPrivateKey(), null) == null
                || EnvironmentVariable.getProperty(RSAUtil.getCurrentPublicKey(), null) == null
                || "".equals(EnvironmentVariable.getProperty(RSAUtil.getCurrentPrivateKey(), null))
                || "".equals(EnvironmentVariable.getProperty(RSAUtil.getCurrentPublicKey(), null))
                ) {
            //当前用户不存在 这个key

            //todo 2018、0509 生成 RSApublicKey
            String[] s = RSAUtil.genKeyPair();
            if (s == null) {
                ToastUtil.showToast(context, "生成RSA密钥失败");
                return;
            }
            String rsaPrivateKey = s[0];
            String rsaPublicKey = s[1];

            //保存
            EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), rsaPrivateKey);
            EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), rsaPublicKey);

            String ethAddress = EnvironmentVariable.getProperty("tc_ethAddress", "");
            String publicKey = EnvironmentVariable.getProperty("tc_ethPublicKey", "");
            sendRsaPublicKeyToServer(context, rsaPublicKey, listener);
        }
//        else if("".equals(EnvironmentVariable.getProperty("tc_ethPublicKey",""))){
//
//        }

        else {
            if (listener != null) {
                listener.checkSuccess();
            }

        }


    }

    /**
     * 通讯公钥发送给臧老师服务器
     * @param context
     * @param rsaPublicKey
     * @param listener
     */
    public static void sendRsaPublicKeyToServer(final Context context, final String rsaPublicKey, final CheckListener listener) {
        if (context != null) {
            TCLoadingDataView.show(context, "数据初始化中..");
        }
        HashMap<String, String> map = new HashMap<>();
        map.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        map.put("comPublicKey", rsaPublicKey);

        TCRequestUtil.postOAuthRequest(TAG, "user/updateUserComPublicKey", map,
                new TCRequestUtil.TCRequestCallback() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onSuccess(String response) {
                        if (context != null) {
                            TCLoadingDataView.dismiss();
                        }

                        try {
                            JSONObject jsonObject = new JSONObject(response);

                            if (jsonObject.has("result")
                                    && jsonObject.getString("result")
                                    .equals("success")) {
//                                Log.i(TAG, "comPublicKey=" + rsaPublicKey);
//                                Log.i(TAG, "更新服务器comPublicKey成功");
                                if (listener != null) {
                                    listener.checkSuccess();
                                }
                            } else {

//                                EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
//                                EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                                if (listener != null) {
                                    listener.checkFail();
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
//                            EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
//                            EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                            if (listener != null) {
                                listener.checkFail();
                            }
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        if (context != null) {
                            TCLoadingDataView.dismiss();
                        }
//                        EnvironmentVariable.setProperty(RSAUtil.getCurrentPrivateKey(), null);
//                        EnvironmentVariable.setProperty(RSAUtil.getCurrentPublicKey(), null);
                        if (listener != null) {
                            listener.checkFail();
                        }

                    }
                });
    }

    /**
     * 通讯公钥发送到服务器
     *
     * @param rsaPublicKey 通讯公钥
     */
    public static void sendRsaPublicKeyToServer(String rsaPublicKey) {
        sendRsaPublicKeyToServer(null, rsaPublicKey, null);
    }


    public interface CheckListener {
        void checkSuccess();
        void checkFail();
    }


    /**
     * 读取本地的keystore
     *
     * @param context
     * @return
     */
//    public static List<WalletBean> getWallet(Context context) {
//        List<WalletBean> list = new ArrayList<>();
//        String fileFolder = TalkChainConstant.getDataFilePath(context.getApplicationContext()) + File.separator + EnvironmentVariable.getUserName();
//        File file = new File(fileFolder);
//        if (file == null) {
//            return list;
//        }
//        if (!file.isDirectory()) {
//            FileDeleteUtil.delete(file);
//            file.mkdirs();
//            return list;
//        }
//        File[] files = file.listFiles();
//        if (files != null && files.length > 0) {
//            for (int i = 0; i < files.length; i++) {
//                WalletBean walletBean = new WalletBean();
//                try {
//                    String text = readFile(files[i].getAbsolutePath());
//                    JSONObject jsonObject = new JSONObject(text);
//                    if (jsonObject != null && jsonObject.has("address")) {
//                        walletBean.setAddress("0x" + jsonObject.getString("address"));
//                        walletBean.setFile(files[i]);
//                        walletBean.setFilePath(files[i].getAbsolutePath());
//                        Account account = new AccountDao(context).getAccount(walletBean.getAddress().toLowerCase());
//                        if (account != null) {
//                            walletBean.setAccountName(account.getAcccountName());
//                            walletBean.setAvatar(account.getAccountAvatar());
//                        } else {
//                            walletBean.setAccountName("账户");
//                            walletBean.setAvatar("");
//                        }
//
//                        list.add(walletBean);
//                    } else {
//                        continue;
//                    }
//
//
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    continue;
//                }
//            }
//            return list;
//
//        } else {
//            return list;
//        }
//    }

    /**
     * 比对本地keystore中的ethaddress和服务器ethadress是否相同
     *
     * @param serverEthAddress 服务器上的钱包地址
     * @return 与服务器对比是否一致
     */
    public static boolean compareLocalFileEthAddressWithServer(Context mContext, String serverEthAddress) {
        try {
//            List<WalletBean> list = getWallet(mContext);
//            if (list == null) {
//                return false;
//            }
//            if (list.size() == 0) {
//                return false;
//            }
//            if (list.get(0).getAddress().toLowerCase().equals(serverEthAddress.toLowerCase())) {
//                return true;
//            } else {
//                return false;
//            }
            //查询主钱包
            Account account = new AccountDao(mContext).getMainAccount();

            if (account != null) {
                if (account.getAddress().toLowerCase().equals(serverEthAddress.toLowerCase())) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
